﻿using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace MyDemo.Tasks
{
    public class TaskExample
    {


        /// <summary>
        /// 顺序任务执行
        /// </summary>
        public static void Demo1()
        {
            //顺序任务执行
            Task.Factory.StartNew(() =>
            {
                Console.WriteLine(1);
                return 1;
            })
            .ContinueWith((task) =>
            {
                Console.WriteLine($"主任务返回结果值：{task.Result}");
                Stopwatch wt = new Stopwatch();
                wt.Start();
                Thread.Sleep(1000 * 5);               //等待5s以后才会依次输出2，3
                wt.Stop();
                Console.WriteLine("等待了：{0}ms，输出结果{1}", wt.ElapsedMilliseconds, 2);
            })
            .ContinueWith((task) =>
            {
                Console.WriteLine(3);
            })
            .Wait(); // Wait会阻塞等待，直到所有任务执行完毕
        }



        /// <summary>
        /// 并行任务
        /// </summary>
        public static void Demo2()
        {
            //并行任务
            var len = 5;
            var tasks = new Task<int>[len];
            var watch = new Stopwatch();

            Func<object, int> fun = (num) =>
            {
                Thread.Sleep(1000 * 2);
                Console.WriteLine("第{0}个", num);
                return Convert.ToInt32(num);
            };

            watch.Start();
            for (int i = 0; i < len; i++)
            {
                tasks[i] = Task.Factory.StartNew<int>(fun, i);      //Task.Factory.StartNew直接开启Task任务无需在使用start
            }
            Task.WaitAll(tasks, 1000 * 10);  //10s等待
            watch.Stop();

            Console.WriteLine("tasks共使用时间：{0}s={1}ms", watch.ElapsedMilliseconds / 1000, watch.ElapsedMilliseconds);
        }
    }
}